package com.jn.news.ui;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;


import com.jn.news.R;
import com.jn.news.utils.DatabaseHelper;
import com.jn.news.utils.StatusBarUtils;
import com.jn.news.utils.ToastUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 注册页面
 */
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText etUsername;  //用户名
    private EditText etPassword; //密码
    private EditText etPhone;  //手机号
    private EditText etQQ; //QQ
    private EditText etMail; //邮箱
    private TextView tvRegister;
    private SQLiteDatabase db;
    private RelativeLayout rlLeft;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置状态栏颜色
        StatusBarUtils.with(this).init3(2, 102);
        setContentView(R.layout.activity_register);
        initView();
        initData();
    }

    /**
     * 初始化View
     */
    private void initView(){
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        etPhone = findViewById(R.id.et_phone);
        etQQ = findViewById(R.id.et_qq);
        etMail = findViewById(R.id.et_email);
        tvRegister = findViewById(R.id.tv_register);
        rlLeft = findViewById(R.id.rl_left);
    }
    private void initDB(){
        //初始化创建表
        SQLiteOpenHelper dbHelper = new DatabaseHelper(this);
        // 调用getReadableDatabase()或getWritableDatabase()才算真正创建或打开数据库
        db = dbHelper.getWritableDatabase();
    }
    private void initData(){
        // 注册点击事件
        tvRegister.setOnClickListener(this);
        rlLeft.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.tv_register){
            // 非空校验
            if(TextUtils.isEmpty(etUsername.getText().toString().trim())){
                ToastUtil.showToast(this,"用户名不能为空");
                return;
            }
            //非空校验
            if(TextUtils.isEmpty(etPassword.getText().toString().trim())){
                ToastUtil.showToast(this,"密码不能为空");
                return;
            }
            //非空校验
            if(TextUtils.isEmpty(etPhone.getText().toString().trim())){
                ToastUtil.showToast(this,"手机号不能为空");
                return;
            }
            // 正则表达式校验手机号是否合法
            String regex = "^1[3-9]\\d{9}$"; //表示1开头第二位数字是3-9的数字，后面再跟9位数字
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(etPhone.getText().toString().trim());
            if(!matcher.matches()){
                ToastUtil.showToast(this,"手机号格式不正确");
                return;
            }
            //非空校验
            if (TextUtils.isEmpty(etQQ.getText().toString().trim())){
                ToastUtil.showToast(this,"QQ不能为空");
                return;
            }
            //非空校验
            if (TextUtils.isEmpty(etMail.getText().toString().trim())){
                ToastUtil.showToast(this,"邮箱不能为空");
                return;
            }
            initDB();
            // 注册的时候要先判断用户名是否存在
            if(isNameExists(db,etUsername.getText().toString().trim())){
                ToastUtil.showToast(this,"用户名已存在");
                return;
            }
            //  如果不存在，往数据库插入数据
            ContentValues values = new ContentValues();
            values.put("name", etUsername.getText().toString().trim());
            values.put("password", etPassword.getText().toString().trim());
            values.put("phone", etPhone.getText().toString().trim());
            values.put("qq", etQQ.getText().toString().trim());
            values.put("email", etMail.getText().toString().trim());
            long result = db.insert("user", null, values);
            if(result > 0){
                ToastUtil.showToast(this,"注册成功");
            }else{
                ToastUtil.showToast(this,"注册失败");
            }
            //关闭数据库连接
            db.close();
            finish();
        }else if(v.getId() == R.id.rl_left){
            //关闭页面
            finish();
        }
    }
    /**
     * 判断用户名是否存在
     * @param db
     * @param name
     * @return
     */
    public boolean isNameExists(SQLiteDatabase db, String name) {
        // sql语句 查询name字段为name的值是否存在
        String sql = "SELECT EXISTS(SELECT 1 FROM user WHERE name = ?)";
        Cursor cursor = db.rawQuery(sql, new String[]{name});
        boolean exists = false;
        if (cursor != null && cursor.moveToFirst()) {
            exists = (cursor.getInt(0) == 1);
        }
        if (cursor != null) {
            cursor.close();
        }
        return exists;
    }
}